<template>
  <div class="home-container">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-content">
        <h1>欢迎来到在线商城</h1>
        <p>发现优质商品，享受便捷购物体验</p>
        <div class="welcome-actions">
          <el-button type="primary" size="large" @click="$router.push('/products')">
            <el-icon><IconGoods /></el-icon>
            浏览商品
          </el-button>
          <el-button size="large" @click="$router.push('/login')" v-if="!userStore.isAuthenticated()">
            <el-icon><IconUser /></el-icon>
            立即登录
          </el-button>
          <el-button type="success" size="large" @click="demoCheckout" style="margin-left: 15px;">
            演示结算流程
          </el-button>
        </div>
      </div>
    </div>

    <!-- 功能导航 -->
    <div class="features-section">
      <h2>商城功能</h2>
      <div class="features-grid">
        <div class="feature-card" @click="$router.push('/products')">
          <el-icon class="feature-icon"><IconGoods /></el-icon>
          <h3>商品浏览</h3>
          <p>浏览丰富的商品分类，找到心仪的商品</p>
        </div>
        <div class="feature-card" @click="$router.push('/cart')" v-if="userStore.isAuthenticated()">
          <el-icon class="feature-icon"><ShoppingCart /></el-icon>
          <h3>购物车</h3>
          <p>管理您的购物车，随时查看已选商品</p>
        </div>
        <div class="feature-card" @click="$router.push('/orders')" v-if="userStore.isAuthenticated()">
          <el-icon class="feature-icon"><IconDocument /></el-icon>
          <h3>订单管理</h3>
          <p>查看订单状态，跟踪物流信息</p>
        </div>
        <div class="feature-card" @click="$router.push('/login')" v-if="!userStore.isAuthenticated()">
          <el-icon class="feature-icon"><IconUser /></el-icon>
          <h3>用户中心</h3>
          <p>登录后享受更多个性化服务</p>
        </div>
      </div>
    </div>

    <!-- 热门商品 -->
    <div class="hot-products-section" v-if="hotProducts.length > 0">
      <h2>热门商品</h2>
      <div class="products-grid">
        <div 
          v-for="product in hotProducts" 
          :key="product.id" 
          class="product-card"
          @click="viewProduct(product.id)"
        >
          <div class="product-image">
            <img :src="product.image || '/default-product.jpg'" :alt="product.name" />
          </div>
          <div class="product-info">
            <h3>{{ product.name }}</h3>
            <p class="price">¥{{ product.price }}</p>
            <p class="category">{{ product.category }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import request from '@/utils/request';
import { ShoppingCart } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

export default {
  name: 'HomePage',
  components: {
    ShoppingCart
  },
  setup() {
    const router = useRouter();
    const userStore = useUserStore();
    
    const hotProducts = ref([]);

    const fetchHotProducts = async () => {
      try {
        const response = await request.get('products?page=1&size=4&sortBy=sales_count_desc');
        if (response.code === 200) {
          hotProducts.value = response.data.records || response.data;
        }
      } catch (error) {
        console.error('获取热门商品失败:', error);
      }
    };

    const viewProduct = (id) => {
      router.push(`/product/${id}`);
    };

    const demoCheckout = async () => {
      if (!userStore.isAuthenticated()) {
        ElMessage.warning('请先登录');
        router.push('/login');
        return;
      }

      try {
        // 添加一些测试商品到购物车
        const testProducts = [
          { productId: 1, quantity: 2 },
          { productId: 2, quantity: 1 }
        ];

        for (const item of testProducts) {
          await request.post('/cart/items', null, {
            params: {
              userId: userStore.userId,
              productId: item.productId,
              quantity: item.quantity
            }
          });
        }

        ElMessage.success('已添加演示商品到购物车，正在跳转...');
        setTimeout(() => {
          router.push('/cart');
        }, 1500);
      } catch (error) {
        ElMessage.error('演示失败: ' + (error.response?.data?.message || '网络错误'));
      }
    };

    onMounted(() => {
      fetchHotProducts();
    });

    return {
      userStore,
      hotProducts,
      viewProduct,
      demoCheckout
    };
  }
};
</script>

<style scoped>
.home-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.welcome-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
  padding: 60px 40px;
  text-align: center;
  margin-bottom: 40px;
}

.welcome-content h1 {
  font-size: 36px;
  font-weight: bold;
  margin-bottom: 15px;
}

.welcome-content p {
  font-size: 18px;
  margin-bottom: 30px;
  opacity: 0.9;
}

.welcome-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
}

.features-section {
  margin-bottom: 40px;
}

.features-section h2 {
  text-align: center;
  font-size: 28px;
  color: #303133;
  margin-bottom: 30px;
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.feature-card {
  background: white;
  border-radius: 12px;
  padding: 30px 20px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.feature-icon {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 15px;
}

.feature-card h3 {
  font-size: 18px;
  color: #303133;
  margin-bottom: 10px;
}

.feature-card p {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.hot-products-section {
  margin-bottom: 40px;
}

.hot-products-section h2 {
  text-align: center;
  font-size: 28px;
  color: #303133;
  margin-bottom: 30px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.product-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.product-image {
  height: 200px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  padding: 20px;
}

.product-info h3 {
  font-size: 16px;
  color: #303133;
  margin-bottom: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
  margin-bottom: 8px;
}

.category {
  font-size: 12px;
  color: #909399;
  margin: 0;
}

@media (max-width: 768px) {
  .welcome-section {
    padding: 40px 20px;
  }
  
  .welcome-content h1 {
    font-size: 28px;
  }
  
  .welcome-content p {
    font-size: 16px;
  }
  
  .welcome-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .features-grid {
    grid-template-columns: 1fr;
  }
  
  .products-grid {
    grid-template-columns: 1fr;
  }
}
</style>